package com.luo.demo.controller;

import com.luo.demo.common.exception.BusinessException;
import com.luo.demo.common.result.Result;
import com.luo.demo.common.util.JwtUtil;
import com.luo.demo.entity.User;
import com.luo.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private JwtUtil jwtUtil;
    // 登录接口
    @PostMapping("/login")
    public Result<String> login(@RequestParam String username, @RequestParam String password) {
        // 验证用户名和密码
        User user = userService.getUserByUsername(username);
        if (user == null || !user.getPassword().equals(password)) {
            throw new BusinessException(401, "用户名或密码错误");
        }

        // 生成 Token
        String token = jwtUtil.generateToken(username);
        return Result.success(token);
    }

    // 获取当前用户信息
    @GetMapping("/info")
    public Result<User> getCurrentUserInfo(HttpServletRequest request) {
        String username = (String) request.getAttribute("username");
        User user = userService.getUserByUsername(username);
        return Result.success(user);
    }

    // 获取所有用户
    @GetMapping("/list")
    public Result<List<User>> list() {
        List<User> users = userService.listAllUsers();
        return Result.success(users);
    }

    // 根据ID获取用户
    @GetMapping("/{id}")
    public Result<User> getById(@PathVariable Integer id) {
        User user = userService.getUserById(id);
        if (user == null) {
            throw new BusinessException(404, "用户不存在");
        }
        return Result.success(user);
    }

    // 添加用户
    @PostMapping("/add")
    public Result<Boolean> add(@RequestBody User user) {
        boolean result = userService.addUser(user);
        return Result.success(result);
    }

    // 更新用户
    @PutMapping("/update")
    public Result<Boolean> update(@RequestBody User user) {
        boolean result = userService.updateUser(user);
        return Result.success(result);
    }

    // 删除用户
    @DeleteMapping("/delete/{id}")
    public Result<Boolean> delete(@PathVariable Integer id) {
        boolean result = userService.deleteUserById(id);
        return Result.success(result);
    }
}